package com.android.often.util.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

public class TabController extends LinearLayout
{

	public interface OnTabChangeListener
	{
		public void onSelectedTabIndexChanged(int newIndex, int oldIndex);
	}

	private OnTabChangeListener mTabChangeListener;
	private int mSelectedIndex = -1;

	public TabController(Context context)
	{
		super(context);
	}

	public void setOnTabChangeListener(OnTabChangeListener tabChangeListener)
	{
		mTabChangeListener = tabChangeListener;
	}

	public void setSelectedIndex(int selectedIndex)
	{
		if (selectedIndex == mSelectedIndex)
		{
			return;
		}
		int oldIndex = mSelectedIndex;
		mSelectedIndex = selectedIndex;
		View oldView = getChildAt(oldIndex);
		if (oldView != null)
		{
			oldView.setSelected(false);
		}
		View newView = getChildAt(selectedIndex);
		if (newView != null)
		{
			newView.setSelected(true);
		}
		if (mTabChangeListener != null)
		{
			mTabChangeListener.onSelectedTabIndexChanged(selectedIndex, oldIndex);
		}

	}

	public TabController(Context context, AttributeSet attrs)
	{
		super(context, attrs);
	}

	@Override
	protected void onFinishInflate()
	{
		super.onFinishInflate();
		int childCount = getChildCount();
		for (int i = 0; i < childCount; i++)
		{
			View child = getChildAt(i);
			child.setTag(i);
			child.setOnClickListener(tabClicked);
		}
	}

	private OnClickListener tabClicked = new OnClickListener()
	{

		@Override
		public void onClick(View v)
		{
			// TODO Auto-generated method stub
			int index = (Integer) v.getTag();
			if (mSelectedIndex == index)
			{
				return;
			}
			int oldIndex = mSelectedIndex;
			View oldView = getChildAt(oldIndex);
			if (oldView != null)
			{
				oldView.setSelected(false);
			}
			View newView = getChildAt(index);
			if (newView != null)
			{
				newView.setSelected(true);
			}
			mSelectedIndex = index;
			if (mTabChangeListener != null)
			{
				mTabChangeListener.onSelectedTabIndexChanged(index, oldIndex);
			}
		}

	};
}
